#include "parser.h"
#include <stdlib.h>

using std::istream;
using std::string;

Parser :: Parser(istream &is) : mState(ignoreState),mPos(0),mLineNo(0),mtext(is)
{
	
}

bool Parser :: Readline()
{
	if(getline(mtext,mLine))
	{
		mPos = 0;
		mLineNo = mLineNo + 1;
		mLine = mLine+'x';
		return true;
	}
	else if(mtext.eof())
	{
		std::cout << "Reached the end of file\n";
		return false;
	}
}

char Parser :: NextChar()
{
	if (mPos >= mLine.size())
	{
		if(!Readline())
		{
			return 0;
		}
	}
	return mLine[mPos++];
}

int Parser :: GetElement()
{
	int element = 0;
	while(char c = NextChar())
	{
		switch(mState)
		{
			case ignoreState:
				if (c == ' ')
				{
					mState = readState;
				}
				if (c == 'x')
				{
					//This case means that we have an empty timestep;
					mState = ignoreState;
					return -2;
				}
				break;
			case readState:
				if (std :: isdigit(c))
				{
					element = element + atoi(&c);
					element = element * 10;
				}
				else if (c == ' ')
				{
					element = element/10;
					return element;
				}
				else if (c == 'x')
				{
					element = element/10;
					mState = ignoreState;
					return element;
				}
				else
				{
					std :: cout << "Incorrect File Format\n";
				}
				break;
			default:
				std :: cout << "Error in Parser. Parser entered default state\n";
		}
	}
	
	return -1;
}

unsigned int Parser :: LineNo() const
{
	return mLineNo;
}

string Parser :: Context() const
{
	return mLine;
}

